/*
 *
 *
 */
#include "GameManager.h"

#ifndef _GAMEMANAGER_CPP_
#define _GAMEMANAGER_CPP_


/*
 *
 */
GameManager::GameManager(void)
{
    quit    = 0;
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();
    if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) < 0)
        fprintf(stderr,"Erro ao iniciar biblioteca mixer: %s\n",Mix_GetError());
    screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
    manex = (FPSmanager*) malloc(sizeof(FPSmanager));
  
}

/*
 *
 */
GameManager::~GameManager(void)
{
    if(manex != 0)
        free(manex);
    SDL_FreeSurface(screen);
    if (currentState != NULL)
    {
        delete currentState;
        currentState = NULL;
    }
    Mix_CloseAudio();
    TTF_Quit();
    SDL_Quit();
}

/*
 *
 */
void GameManager::run(void)
{
    Uint32 tCurrent = SDL_GetTicks(), tPrevious = SDL_GetTicks(), tDelta = 0;

    int idNewState = 0; 		/*valor default, ou seja, não troca estado*/
    currentState = new TitleState();//InitialState();//PreGameState();
    currentState->load();
    
    SDL_initFramerate(manex);           /*indica a estrutura que auxiliará na contagem do frame rate*/
    SDL_setFramerate(manex, FRAME_RATE);  /*seta a taxa frames por segundo*/
    
    while(quit == 0)			        /*loop principal do jogo*/
    {
        idNewState = currentState->update(tDelta);
        currentState->draw(screen);

        if(idNewState != 0)		/*se o valor de idNewState for diferente do default então devemos trocar o estado*/
		{
            /*troca o estado*/
            currentState->unload();
            delete currentState;
            currentState = NULL;
            tPrevious = SDL_GetTicks(); /*para não dar problema em tDelta na troca de estados*/
            switch(idNewState)
            {
                case -1:    /*sai do loop principal do jogo*/
                    quit = 1;
                    break;
                case 1:
                    currentState = new InitialState();
                    currentState->load();
                    break;
                case 2:
                    currentState = new PreGameState();
                    currentState->load();
                    break;
                case 3:
                    currentState = new TitleState();
                    currentState->load();
                    break;
            }
            idNewState = 0;
        }
        SDL_Flip(screen);
        SDL_framerateDelay(manex);      /*Espera o tempo suficiente para completar um tempo do frame*/
        tCurrent = SDL_GetTicks();
        tDelta = tCurrent - tPrevious;
        tPrevious = tCurrent;

    }
}

#endif

